let fs = require("fs");
let mysqlModel = require("mysql");
let connection = null;
let mysql = {

    init: function demo() {
        connection = mysqlModel.createConnection({ host: '127.0.0.1', user: 'root', password: '123456', database: 'yiqing' });
    },

    unuseQuery: function (sql, value, res) {
        mysql.init();
        connection.connect();
        connection.query(sql, value, function (err, result) {
            // console.log(result);             //已经获取到数据了
            /**
             * [ RowDataPacket { id: 1, nums: 0, date: '2022-3-15', city: '龙岩' },
                 RowDataPacket { id: 2, nums: 3, date: '2022-3-15', city: '厦门' } ]
             */
            let html = '';
            for (let val in result) {
                html += '<tr>'
                html += '<td>' + result[val].city + "</td>"
                html += '<td>' + result[val].nums + "</td>"
                html += '</tr>'
            }

            fs.readFile("./home/html/index.html", function (err, data) {
                console.log(err);
                let datas = data.toString();
                let formatHtml = datas.replace("{{result}}", html);
                connection.end();
                res.write(formatHtml);
                res.end();
            })
        })
    }, 
    query: function name(sql,value) {
        let promise = new Promise(function (resolve, reject) {
            mysql.init();
            connection.connect();
            connection.query(sql, value, function (err, result) {
                if(err) {
                    console.log(err.message);
                } else {
                    resolve(result);
                }
                connection.end();
            })
        })
        return promise;
    }
}
module.exports = mysql;         //不暴露会报错：mysql.query is not a function
